/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.yuecai.modules.yc_goods_enshrine_snapshoot.service;

import com.yuecai.modules.yc_goods.domain.YcGoods;
import com.yuecai.modules.yc_goods.repository.YcGoodsRepository;
import com.yuecai.modules.yc_goods_enshrine_snapshoot.domain.YcGoodsEnshrineSnapshoot;
import com.yuecai.modules.yc_goods_enshrine_snapshoot.repository.YcGoodsEnshrineSnapshootRepository;
import com.yuecai.modules.yc_goods_enshrine_snapshoot.service.dto.YcGoodsEnshrineSnapshootDto;
import com.yuecai.modules.yc_goods_enshrine_snapshoot.service.dto.YcGoodsEnshrineSnapshootQueryCriteria;
import com.yuecai.modules.yc_goods_enshrine_snapshoot.service.mapstruct.YcGoodsEnshrineSnapshootMapper;
import com.yuecai.modules.yc_goods_enshrine_snapshoot.vo.YcGoodsEnshrineSnapshootVo;
import com.yuecai.utils.FileUtil;
import com.yuecai.utils.QueryHelp;
import com.yuecai.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author dm
* @date 2020-07-03
**/
@Service
@RequiredArgsConstructor
public class YcGoodsEnshrineSnapshootService {

    private final YcGoodsEnshrineSnapshootRepository ycGoodsEnshrineSnapshootRepository;
    private final YcGoodsRepository ycGoodsRepository;
    private final YcGoodsEnshrineSnapshootMapper ycGoodsEnshrineSnapshootMapper;

    
    public Map<String,Object> queryAll(YcGoodsEnshrineSnapshootQueryCriteria criteria, Pageable pageable) {
        Page<YcGoodsEnshrineSnapshoot> page = ycGoodsEnshrineSnapshootRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<YcGoodsEnshrineSnapshoot> content = page.getContent();
        List<YcGoodsEnshrineSnapshootVo> list = new ArrayList<>();
        for (YcGoodsEnshrineSnapshoot item : content) {
            Long goodId = item.getGoodId();
            YcGoods goods = ycGoodsRepository.findByIdAndStatusTrue(goodId);
            if (goods != null) {
                YcGoodsEnshrineSnapshootVo itemVo = new YcGoodsEnshrineSnapshootVo();
                BeanUtils.copyProperties(goods, itemVo);
                list.add(itemVo);
            } else {
                ycGoodsEnshrineSnapshootRepository.deleteById(item.getId());
            }
        }

        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", list);
        map.put("totalElements", page.getTotalElements());
        return map;
    }

    
    public List<YcGoodsEnshrineSnapshootDto> queryAll(YcGoodsEnshrineSnapshootQueryCriteria criteria){
        return ycGoodsEnshrineSnapshootMapper.toDto(ycGoodsEnshrineSnapshootRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    
    @Transactional
    public YcGoodsEnshrineSnapshootDto findById(Long id) {
        YcGoodsEnshrineSnapshoot ycGoodsEnshrineSnapshoot = ycGoodsEnshrineSnapshootRepository.findById(id).orElseGet(YcGoodsEnshrineSnapshoot::new);
        ValidationUtil.isNull(ycGoodsEnshrineSnapshoot.getId(),"YcGoodsEnshrineSnapshoot","id",id);
        return ycGoodsEnshrineSnapshootMapper.toDto(ycGoodsEnshrineSnapshoot);
    }

    
    @Transactional(rollbackFor = Exception.class)
    public YcGoodsEnshrineSnapshootDto create(YcGoodsEnshrineSnapshoot resources) {
        return ycGoodsEnshrineSnapshootMapper.toDto(ycGoodsEnshrineSnapshootRepository.save(resources));
    }

    
    @Transactional(rollbackFor = Exception.class)
    public void update(YcGoodsEnshrineSnapshoot resources) {
        YcGoodsEnshrineSnapshoot ycGoodsEnshrineSnapshoot = ycGoodsEnshrineSnapshootRepository.findById(resources.getId()).orElseGet(YcGoodsEnshrineSnapshoot::new);
        ValidationUtil.isNull( ycGoodsEnshrineSnapshoot.getId(),"YcGoodsEnshrineSnapshoot","id",resources.getId());
        ycGoodsEnshrineSnapshoot.copy(resources);
        ycGoodsEnshrineSnapshootRepository.save(ycGoodsEnshrineSnapshoot);
    }

    
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ycGoodsEnshrineSnapshootRepository.deleteById(id);
        }
    }

    
    public void download(List<YcGoodsEnshrineSnapshootDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YcGoodsEnshrineSnapshootDto ycGoodsEnshrineSnapshoot : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户ID", ycGoodsEnshrineSnapshoot.getUserId());
            map.put("商品ID", ycGoodsEnshrineSnapshoot.getGoodId());
            map.put("创建时间", ycGoodsEnshrineSnapshoot.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public long finCount(YcGoodsEnshrineSnapshootQueryCriteria criteria, Pageable pageable) {
        Page<YcGoodsEnshrineSnapshoot> page = ycGoodsEnshrineSnapshootRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return page.getTotalElements();
    }

    /**
     * 查看是否收藏
     * @param userId
     * @param goodId
     * @return
     */
    public Boolean checkOut(Long userId, Long goodId) {
        Optional<YcGoodsEnshrineSnapshoot> byUserIdAndGoodId = ycGoodsEnshrineSnapshootRepository.findByUserIdAndGoodId(userId, goodId);
        if (byUserIdAndGoodId.isPresent()){
            return true;
        }
        return false;
    }
}